<!-- src/views/system/Acl.vue -->
<script setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { AclStores } from '@/stores/AclStores';
import AclEdit from './AclEdit.vue';

const aclStore = AclStores();

const tableData = ref([]);
const searchForm = ref({
  name: '',
  code: '',
  type: null,
  url: ''
});

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const dialogVisible = ref(false);
const currentAcl = ref({});

// 添加日期格式化方法
const formatDateTime = (isoString) => {
  if (!isoString) return '';
  const date = new Date(isoString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const fetchData = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    };

    await aclStore.list(params);

    tableData.value = aclStore.aclList;
    total.value = aclStore.pageInfo.total;

  } catch (error) {
    ElMessage.error('获取权限列表失败: ' + (error.message || '未知错误'));
    console.error('API Error:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

const resetSearch = () => {
  searchForm.value = {
    name: '',
    code: '',
    type: null,
    url: ''
  };
  currentPage.value = 1;
  fetchData();
};

const handleAdd = () => {
  currentAcl.value = {};
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  currentAcl.value = { ...row };
  dialogVisible.value = true;
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除权限"${row.name}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    await aclStore.delete(row.id);
    ElMessage.success('删除成功');
    await fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'));
    }
  }
};

const handleSuccess = () => {
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="acl-management-container">
    <el-card shadow="hover" class="search-card">
      <div class="search-header">
        <h3>权限查询</h3>
        <div class="search-actions">
          <el-button type="primary" @click="fetchData" :loading="loading">
            <el-icon class="el-icon--left">
              <Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon class="el-icon--left">
              <Refresh />
            </el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon class="el-icon--left">
              <Plus />
            </el-icon>
            新增
          </el-button>
        </div>
      </div>

      <el-form :model="searchForm" label-width="100px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="权限名称">
              <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="权限编码">
              <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="权限类型">
              <el-select v-model="searchForm.type" placeholder="请选择权限类型" clearable>
                <el-option label="API" :value="1" />
                <el-option label="菜单" :value="2" />
                <el-option label="按钮" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="hover" class="table-card">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          stripe
          border
          highlight-current-row
      >
        <el-table-column label="ID" prop="id" width="80" align="center" />
        <el-table-column label="权限名称" prop="name" width="150" align="center" />
        <el-table-column label="权限编码" prop="code" width="150" align="center" />
        <el-table-column label="状态" prop="isDelete" width="150" align="center" >
          <template #default="scope">
            {{ scope.row.isDelete === 0 ? '正常' : '禁用' }}

          </template>
        </el-table-column>
        <el-table-column label="权限类型" prop="type" width="120" align="center">
          <template #default="scope">
            {{
              scope.row.type === 1 ? 'API' :
                  scope.row.type === 2 ? '菜单' :
                      scope.row.type === 3 ? '按钮' : '未知'
            }}
          </template>
        </el-table-column>
        <el-table-column label="URL地址" prop="url" width="200" align="center" />
        <el-table-column label="创建时间" prop="createdTime" width="230" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updatedTime" width="230" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.updatedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <AclEdit
        v-model:visible="dialogVisible"
        :acl-data="currentAcl"
        @success="handleSuccess"
    />
  </div>
</template>

<style scoped>
.acl-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 18px;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.el-button {
  padding: 8px 15px;
}
</style>
